/**
 * 
 */
package ae.pcfc.cldos.online.web.controller.client.company.ev.termination;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.WebUtils;
import org.springframework.ws.client.WebServiceIOException;
import org.springframework.ws.soap.client.SoapFaultClientException;

import ae.pcfc.cldos.online.common.ConstantsCommon.Steps;
import ae.pcfc.cldos.online.common.UltimusConstants.AdminDecision;
import ae.pcfc.cldos.online.common.clddb.domain.ServiceMaster;
import ae.pcfc.cldos.online.common.delegate.CompanyAdminDelegate;
import ae.pcfc.cldos.online.common.delegate.EmploymentVisaCancelationDelegate;
import ae.pcfc.cldos.online.common.delegate.FnpGSDelegate;
import ae.pcfc.cldos.online.common.exception.EmployeeAllreadyExistException;
import ae.pcfc.cldos.online.common.exception.GSAppException;
import ae.pcfc.cldos.online.common.exception.InvalidEmpIdException;
import ae.pcfc.cldos.online.common.exception.LicenseErrorRemarkException;
import ae.pcfc.cldos.online.common.exception.LicenseExpiredException;
import ae.pcfc.cldos.online.common.exception.PaymentException;
import ae.pcfc.cldos.online.common.exception.RequestAllreadyExistException;
import ae.pcfc.cldos.online.common.exception.UltimusAppException;
import ae.pcfc.cldos.online.common.vo.AdminDecisionVO;
import ae.pcfc.cldos.online.common.vo.AppSaveResponseVO;
import ae.pcfc.cldos.online.common.vo.FileVO;
import ae.pcfc.cldos.online.common.vo.UserVO;
import ae.pcfc.cldos.online.common.vo.ev.ren.can.EmploymentVisaCancelationVO;
import ae.pcfc.cldos.online.fnp.service.client.vo.FNPCatalogVO;
import ae.pcfc.cldos.online.fnp.service.client.vo.FNPParameterVO;
import ae.pcfc.cldos.online.web.Constants;
import ae.pcfc.cldos.online.web.PageType;
import ae.pcfc.cldos.online.web.ViewPath;
import ae.pcfc.cldos.online.web.ViewUtils;
import ae.pcfc.cldos.online.web.model.EVTerminationModel;
import ae.pcfc.cldos.online.web.services.breadcrumbs.BreadCrumbsFactoryService;
import ae.pcfc.cldos.online.web.services.fnp.FnpParametersCheckService;

/**
 * 
 * @author arosa
 *
 */
@Controller
@RequestMapping(value = ViewPath.__ADMIN_EMPLOYMENT_VISA_TERMINATE_REVIEW)
public class EVTerminationReviewController extends EVTerminationBase{
	
	@Autowired
	@Qualifier("employmentVisaCancelationDelegate")
	private EmploymentVisaCancelationDelegate employmentVisaCancelationDelegate;
	
	@Autowired
	@Qualifier("companyAdminDelegate")
	private CompanyAdminDelegate companyAdminDelegate;
	
	@Autowired
	@Qualifier("FnpGSDelegate")
	private FnpGSDelegate FnpGSDelegate;
	
	@Autowired
	private FnpParametersCheckService fnpParametersCheckService;
	
	@ModelAttribute
	public void populateBreadCrumbs(ModelMap model, @RequestParam String appId) {
		breadCrumbsFactoryService.populateEmploymentVisaTerminationTasktBreadcrumb(model, appId, BreadCrumbsFactoryService.TASK_TYPE_MAIN_ADMIN_APPROVE);
	}
	
	@ModelAttribute("evTerminationModel")
	public EVTerminationModel populateRegisterEmploymentVisaReviewerInfoModel(@RequestParam String appId,
			HttpServletRequest request, ModelMap model) throws Exception {
		EVTerminationModel evTerminationModel = new EVTerminationModel();
		
		EmploymentVisaCancelationVO employmentVisaCancelationVO =
				employmentVisaCancelationDelegate.getEmploymentVisaCancelationAppInfo(
						encryptionDelegate.decodeAndDecrypt(appId), getUserVO(), Steps.MAIN_ADMIN_APPROVE);
		
		List<FileVO> fileVOList = employmentVisaCancelationVO.getFileVOList();
		model.put("files", fileVOList);
		model.put("comments", employmentVisaCancelationVO.getApplicationCommentVOs());
		
		mapper.map(employmentVisaCancelationVO.getEmploymentVisaCancelationDetailsVO(), evTerminationModel);
		model.put("appId", appId);
		return evTerminationModel;
	}
	
	@ModelAttribute(Constants.__FNP_CATALOG_MODEL_KEY)
	public List<FNPCatalogVO> populateFinanceReviewerInfoModel() {
		return FnpGSDelegate.getFnpCatalogVOsByServiceCode(ServiceMaster.EV_CANCELATION.toString());
	}
	
	@RequestMapping(value = "/form.htm", method = RequestMethod.GET)
	public ModelAndView form() {
		return ViewUtils.DEFAULT_VIEW;
	}
	
	@RequestMapping(method = RequestMethod.POST, value = "/form.htm")
	public ModelAndView form(
			HttpServletRequest request,
			SessionStatus status,
			@RequestParam String appId,
			@RequestParam String fnpServiceCode,
			@RequestParam(required=false) String adminComments,
			@ModelAttribute(value="evTerminationModel") EVTerminationModel evTerminationModel,
			BindingResult errors) throws Exception {
		
		System.out.println("review process submitted");
		UserVO userVO = getUserVO();
		AdminDecisionVO adminDecisionVO = new AdminDecisionVO();
		
		boolean isSubmitApproval = WebUtils.hasSubmitParameter(request, "MainUserApprove");
		boolean isSubmitReject = WebUtils.hasSubmitParameter(request, "MainUserReject");
		boolean isSubmitCancel = WebUtils.hasSubmitParameter(request, "MainUserCancel");
		Map<String, String> paramMap = new HashMap<String, String>();
		
		if(isSubmitApproval){
			System.out.println("Main admin Approved...");
			adminDecisionVO.setStrActionType(AdminDecision.APPROVED.getAdminDecision());
		}else if(isSubmitReject){
			if(adminComments==null || adminComments.isEmpty()){
				errors.reject("admin.comment.required");
			}
			System.out.println("Main admin Rejected...");
			adminDecisionVO.setStrActionType(AdminDecision.REJECTED.getAdminDecision());
		} else if(isSubmitCancel){
			System.out.println("Main admin Canceled...");
			adminDecisionVO.setStrActionType(AdminDecision.CANCELLED.getAdminDecision());
		}
		
		if(!errors.hasErrors()){
			if(isSubmitApproval){
				List<FNPParameterVO> allParams = FnpGSDelegate.retreiveFNPParameters(Arrays.asList(new String[]{fnpServiceCode}));
				List<FNPParameterVO> notFeeled = fnpParametersCheckService.feelParamsAndGetNotFeeled(request, allParams);
				if(notFeeled.size()>0){
					errors.reject("sdgsd", "Recomplete payment info please");
				} else {
					adminDecisionVO.setFnpParams(allParams);
				}
			}
			adminDecisionVO.setApplicationId(encryptionDelegate.decodeAndDecrypt(appId));
			adminDecisionVO.setUserVO(userVO);
			adminDecisionVO.setFnpServiceCode(fnpServiceCode);
			adminDecisionVO.setComment(adminComments);
			
			try{
				AppSaveResponseVO appSaveResponseVO = companyAdminDelegate.companyAdminAction(adminDecisionVO);
				paramMap.put(Constants.__REFRENCE_NO, appSaveResponseVO.getReferenceNo());
				paramMap.put(Constants.__INCIDENT_NO, appSaveResponseVO.getIncidentNo());
			} catch (PaymentException e) {
				errors.reject("error.payment");
			}catch(RequestAllreadyExistException e) {
				errors.reject("request.exist");
			}catch (LicenseErrorRemarkException e) {
				errors.reject("license.errorremark");
			}catch (LicenseExpiredException e) {
				errors.reject("license.expire");
			}catch(InvalidEmpIdException e){
				errors.reject("invalid.employee");
			}catch(GSAppException e){
				errors.reject("unable.to.proceed.gs.down");
			}catch(UltimusAppException e){
				errors.reject("unable.to.proceed.ultimus.down");
			}catch(WebServiceIOException e){
				e.printStackTrace();
				errors.reject("unable.to.proceed.gs.fnp.down");
			}catch(SoapFaultClientException e){
				e.printStackTrace();
				errors.reject("unable.to.proceed.gs.fnp.down");
			}catch(Exception e){
				e.printStackTrace();
				errors.reject("unable.to.proceed");
			}
		}
		
		if(!errors.hasErrors()){
			return new ModelAndView(ViewUtils.getRedirect(ViewPath.__CONFIRMATION, PageType.SHOW, paramMap));
		} else {
			return ViewUtils.DEFAULT_VIEW;
		}
	}
	
}
